package cn.kent.high.juc.list;

import java.util.Iterator;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 迭代器测试-写时复制导致的弱一致性问题重现
 *
 * 以下代码导致：线程一遍历的是原始数据，线程二遍历的是最新数据。
 */
public class ListIteratorTest {
    public static void main(String[] args) {
        // Vector<String> list = new Vector<String>();
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                list.add("hello");
                list.add("hello2");
                list.add("hello3");
                System.out.println("thread1开始遍历");
                Iterator<String> iterator = list.iterator();
                while (iterator.hasNext()) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("thread1遍历元素-> "+iterator.next());
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                list.add("thread2-1");
                list.add("thread2-2");
                list.add("thread2-3");
                System.out.println("thread2开始遍历，会遍历6个元素");
                Iterator<String> iterator = list.iterator();
                while (iterator.hasNext()) {
                    System.out.println("thread2遍历元素-> "+iterator.next());
                }
            }
        });
        thread1.start();
        thread2.start();
    }
}
